import { ref } from 'vue';

// 倒计时方法
export default function (s: number, ms = 1000) {
	let countdown = ref(0);
	let timing = ref(false); // 是否在倒计时中
	let timer: NodeJS.Timeout;

	// 开始到计时
	function startCountdown() {
		clearInterval(timer);
		timing.value = true;
		countdown.value = s;
		timer = setInterval(() => {
			// 如果倒计时等于0，则关闭定时器
			if (--countdown.value === 0) {
				clearInterval(timer);
				timing.value = false;
			}
		}, ms);
	}

	// 重置
	function reset() {
		clearInterval(timer);
		timing.value = false;
		countdown.value = 0;
	}

	return {
		countdown,
		timing,
		startCountdown,
		reset,
	};
}
